<template>
  <ul class="list">
    <li
      class="item"
      v-for="item of alphabet"
      :key="item"
      @click="handleClick"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchEnd="handleTouchEnd"
      :ref="item"
    >{{item}}</li>
  </ul>
</template>
<script>
export default {
  name: "cityaphabet",
  props: {
    cities: Object
  },
  created() {
    console.log(this.cities);
  },
  computed: {
    alphabet() {
      for (let key in this.cities) {
        this.alphabets.push(key);
      }
      return this.alphabets;
    }
  },
  data() {
    return {
      alphabets: [],
      isTouching: false,
      startY: null,
      timer: true
    };
  },
  updated() {
    // 性能优化
    this.startY = this.$refs["A"][0].offsetTop;
  },
  methods: {
    handleClick(e) {
      this.$emit("getAlphabetVal", e.target.innerHTML);
    },
    handleTouchStart() {
      this.isTouching = true;
    },
    handleTouchMove(e) {
      if (this.isTouching) {
        if (this.timer) {
          //函数截留
          clearTimeout(this.timer);
        }
      this.timer = setTimeout(() => {
          const Y = 114 - 19;
          const moveY = e.touches[0].clientY - Y;
          const distanceY = moveY - this.startY;
          const index = parseInt(Math.floor(distanceY / 20));
          if (index >= 0 && index <= this.alphabets.length) {
            this.$emit("getAlphabetVal", this.alphabets[index]);
          }
          console.log(this.alphabets[index]);
        }, 16);
      }
    },
    handleTouchEnd() {
      this.isTouching = false;
    }
  }
};
</script>
<style lang="less" scoped>
@import "~styles/varibles.less";
.list {
  position: absolute;
  right: 0;
  bottom: 0;
  top: 1.78rem;
  display: flex;
  flex-direction: column;
  justify-content: center;
  .item {
    line-height: 0.4rem;
    text-align: center;
    color: @bgColor;
  }
}
</style>
